package com.xiaotu.spider.project.pipeline;

import com.xiaotu.common.model.NetTVModel;
import com.xiaotu.common.model.TVAudienceModel;
import com.xiaotu.common.model.TVCityModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.DataRedisKeyUtils;
import com.xiaotu.common.util.SepratorUtil;
import com.xiaotu.spider.APipeline;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 网剧数据存储实体类，各个网剧爬取任务，都通过此类进行存储
 *
 * @auther GaoHJ
 * @create 2017/10/11
 */
@Component("NetTVPipeline")
public class NetTVPipeline extends APipeline
{
    @Override
    protected void doProcess(ResultItems resultItems, Task task)
    {
        NetTVModel tv = resultItems.get(NetTVModel.class.getName());
        String key = DataRedisKeyUtils.getKey(Constants.DataRedisKey.NetTV_NetPlay_YYYYMMDD);
        if (tv != null)
        {
            cacheHandler.hSet(key, DataRedisKeyUtils.getNetTVKey(tv), tv);
            cacheHandler.setCacheTimeout(key);
        }

        List<NetTVModel> tvList = resultItems.get(NetTVModel.class.getName() + "List");
        if (tvList != null)
        {
            Map<String, NetTVModel> tvMap = tvList.stream().collect(Collectors.toMap(tvModel ->
                    DataRedisKeyUtils.getNetTVKey(tvModel), tvModel -> tvModel));
            cacheHandler.hMSet(key, tvMap);
            cacheHandler.setCacheTimeout(key);
        }

        TVAudienceModel tvAud = resultItems.get(TVAudienceModel.class.getName());
        if (tvAud != null)
        {
            key = DataRedisKeyUtils.getKey(Constants.DataRedisKey.TV_AUDIENCE_YYYYMMDD);
            cacheHandler.hSet(key, tvAud.getSiteDataId(), tvAud);
            cacheHandler.setCacheTimeout(key);
        }

        List<TVCityModel> tvCityList = resultItems.get(TVCityModel.class.getName());
        if (tvCityList != null)
        {
            key = DataRedisKeyUtils.getKey(Constants.DataRedisKey.TV_CITY_YYYYMMDD);
            Map<String, TVCityModel> tvMap = tvCityList.stream().collect(Collectors.toMap(tvModel
                    -> DataRedisKeyUtils.getTVCityKey(tvModel), tvModel -> tvModel));
            cacheHandler.hMSet(key, tvMap);
            cacheHandler.setCacheTimeout(key);
        }
    }
}
